/**
 * @Title: index.js
 * @Description: index.
 * @author: Fanchao
 * @date: 2020/12/13 8:13 下午
 * @version V1.0
 */
import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { Button, Cascader, Form, Input, message, Modal, Popconfirm, Select, Table } from 'antd';
import {
    createMajorDirection,
    deleteMajorDirection,
    getDepartmentTreeList,
    getMajorDirectionList,
    getTrainingTypeList,
} from 'api/index';
import SectionTitle from 'components/SectionTitle';
import AddSomeButton from 'components/AddSomeButton';
import { getChildCascader } from 'utils/index';

const { Option } = Select;

const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
};
const TrainMajor = () => {
    const [loading, setLoading] = useState(false);
    const [dataSource, setDataSource] = useState([]);
    const [visible, setVisible] = useState(false);
    const [trainingTypeList, setTrainingTypeList] = useState([]);
    const [trainingTypeId, setTrainingTypeId] = useState('');
    const [treeData, setTreeData] = useState([]);
    const [form] = Form.useForm();
    const fetch = async (filter) => {
        setLoading(true);
        const result = await getMajorDirectionList({ trainingTypeId: filter });
        if (result.status === 'success') {
            const dataSource = result.result;
            setDataSource(dataSource);
        } else {
            message.error(result.message);
        }
        setLoading(false);
    };
    const fetchTrainingTypeList = async () => {
        const result = await getTrainingTypeList();
        if (result.status === 'success') {
            const trainingTypeList = result.result;
            setTrainingTypeList(trainingTypeList);
        } else {
            message.error(result.message);
        }
    };
    const getUnitsTreeData = async () => {
        const result = await getDepartmentTreeList();
        if (result.status === 'success') {
            const data = result.result;
            const treeData = data.map(c => {
                if (!c.hasLowerDepartment) {
                    return {
                        value: c.departmentId,
                        label: c.departmentName,
                    };
                } else {
                    return {
                        value: c.departmentId,
                        label: c.departmentName,
                        children: getChildCascader(c.lowerDepartmentModel),
                    };
                }
            });
            setTreeData(treeData);
        } else {
            message.error(result.message);
        }
    };
    useEffect(() => {
        getUnitsTreeData();
        fetchTrainingTypeList();
        fetch('');
    }, []);
    const changeSelect = (e) => {
        setTrainingTypeId(e);
    };
    const addItem = () => {
        setVisible(true);
    };
    const handleDelete = async ({ majorDirectionId }) => {
        const result = await deleteMajorDirection({ majorDirectionId });
        if (result.status === 'success') {
            message.success('删除成功');
            fetch('');
            setTrainingTypeId('');
        } else {
            message.error(result.message);
        }
    };
    const title = '新增专业方向';
    const columns = [
        {
            title: '专业方向名称',
            dataIndex: 'majorName',
            align: 'left',
        }, {
            title: '系统编码',
            dataIndex: 'sysCode',
            align: 'left',
        }, {
            title: '专业方向代码',
            dataIndex: 'majorCode',
            align: 'left',
        }, {
            title: '培训类型',
            dataIndex: 'trainingTypeName',
            align: 'left',
        }, {
            title: '负责单位',
            dataIndex: 'manageDepartment',
            align: 'left',
        },

        {
            title: '操作',
            align: 'left',
            render: (item) => {
                return (
                    <div>
                        <Popconfirm title="是否要删除？" onConfirm={() => handleDelete(item)}>
                            <Button style={{ padding: 2, color: '#C21217', fontWeight: 'bold' }} type="link">删除</Button>
                        </Popconfirm>

                    </div>
                );
            },
        },
    ];
    return (
        <div className={styles.pageContainer}>
            <div className={styles.pageContainerHeader}>
                <SectionTitle title={title}/>
                <div style={{ width: '220px' }} onClick={() => addItem({})}>
                    <AddSomeButton title={title}/>
                </div>
            </div>
            <div className={styles.pageContainerTable}>
                <SectionTitle title={'已有专业方向'}/>
                <div className={styles.filterContainer}>
                    <Select
                        placeholder="培训类型"
                        className={styles.formWrapper}
                        value={trainingTypeId}
                        onChange={changeSelect}
                    >
                        {
                            trainingTypeList.map(item => {
                                return <Option key={item.trainTypeId}
                                               value={item.trainTypeId}>{item.trainingTypeName}</Option>;
                            })
                        }
                    </Select>
                    <Button
                        className={styles.marginRight}
                        type="primary"
                        onClick={() => {
                            fetch(trainingTypeId);
                        }}
                    >
                        查询
                    </Button>
                    <Button
                        onClick={() => {
                            fetch('');
                            setTrainingTypeId('');
                        }}
                    >
                        重置
                    </Button>
                </div>
                <div className={styles.tableContainer}>
                    <Table
                        bordered={false} // 是否有边框
                        rowKey='majorDirectionId' // 唯一key值
                        loading={loading} // 加载动画
                        columns={columns} // 表头
                        dataSource={dataSource}
                        pagination={false}
                    />
                </div>
            </div>
            <Modal
                title={title}
                visible={visible}
                // width="960px"
                onOk={() => {
                    form.validateFields().then(async values => {
                        values.leastDepartmentId = values.leastDepartmentId.pop();
                        const result = await createMajorDirection(values);
                        if (result.status === 'success') {
                            setVisible(false);
                            fetch('');
                        } else {
                            message.error(result.message);
                        }
                    }).catch(info => {
                        // console.log(info);
                    });
                }}
                onCancel={() => {
                    form.resetFields();
                    setVisible(false);
                }}
            >
                <Form
                    {...layout}
                    layout="horizontal"
                    form={form}
                    name="basic"
                    initialValues={{}}
                >
                    <Form.Item
                        label="培训类型"
                        name="trainingTypeId"
                        rules={[{ required: true, message: '必填' }]}
                    >
                        <Select
                            placeholder="培训类型"
                        >
                            {
                                trainingTypeList.map(item => {
                                    return <Option key={item.trainTypeId}
                                                   value={item.trainTypeId}>{item.trainingTypeName}</Option>;
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="专业方向"
                        name="majorName"
                        rules={[{ required: true, message: '必填' }]}
                    >
                        <Input placeholder="请输入专业方向名称"/>
                    </Form.Item>
                    <Form.Item
                        label="系统编码"
                        name="sysCode"
                        rules={[{ required: true, message: '必填' }]}
                    >
                        <Input placeholder="请输入系统编码"/>
                    </Form.Item>
                    <Form.Item
                        label="专业方向代码"
                        name="majorCode"
                        // rules={[{ required: true, message: '必填' }]}
                    >
                        <Input placeholder="请输入专业方向代码"/>
                    </Form.Item>
                    <Form.Item
                        label="所属单位"
                        name="leastDepartmentId"
                        rules={[{ required: true, message: '必填' }]}
                    >
                        <Cascader
                            changeOnSelect
                            options={treeData}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default TrainMajor;
